package com.qiantu.phone.ui.activity;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.SystemClock;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.hjq.base.BaseDialog;
import com.hjq.http.lifecycle.ApplicationLifecycle;
import com.hjq.http.listener.HttpCallback;
import com.hjq.widget.layout.SettingBar;
import com.lxj.xpopup.XPopup;
import com.qiantu.api.db.HandleListener;
import com.qiantu.api.db.LLControllerDBManager;
import com.qiantu.api.db.LLDeviceActionDBManager;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.ControllerBean;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.ProtocolSwitchResultBean;
import com.qiantu.api.entity.UniversalDeviceAction;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.bean.AddDeviceBean;
import com.qiantu.phone.event.RefreshControllerEvent;
import com.qiantu.phone.event.RefreshDeviceListEvent;
import com.qiantu.phone.manager.ActivityManager;
import com.qiantu.phone.ui.dialog.BottomEditDialog;
import com.qiantu.phone.ui.dialog.BottomProtocolSwitchDialog;
import com.qiantu.phone.ui.dialog.ConfirmCancelHintDialog;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;
import com.qiantu.phone.utils.AddDeviceParseUtil;
import com.qiantu.phone.utils.Constants;
import com.qiantu.phone.utils.SPUtils;
import com.rich.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;

public class ControllerOtherSettingActivity  extends AppActivity {
    private SettingBar itemAllocationController;
    private SettingBar itemExpandController;
    private SettingBar itemCleanController;
    private SettingBar itemResetController;
    private SettingBar itemAllSearch;
    private SettingBar itemWifiChange;
    private ControllerBean mControllerBean;
    private String controllerSerialNo;
    private Map<String,Map<String, Long>> operationData;

    public static void start(Context context, String controllerSerialNo) {
        Intent intent = new Intent(context, ControllerSettingActivity.class);
        intent.putExtra("controllerSerialNo", controllerSerialNo);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_controller_other_setting;
    }

    @Override
    protected void initView() {
        controllerSerialNo = getString("controllerSerialNo");
        itemAllocationController = findViewById(R.id.item_allocation_controller);
        itemExpandController = findViewById(R.id.item_expand_controller);
        itemCleanController = findViewById(R.id.item_clean_controller);
        itemResetController = findViewById(R.id.item_reset_controller);
        itemAllSearch = findViewById(R.id.item_all_search);
        itemWifiChange = findViewById(R.id.item_wifi_change);
        setOnClickListener(itemAllocationController, itemExpandController, itemCleanController,itemResetController,itemAllSearch,itemWifiChange);
    }

    @Override
    protected void initData() {
        mControllerBean = LLControllerDBManager.getInstance(getContext()).getControllerBySerialNo(controllerSerialNo);
        String operationStr = SPUtils.getInstance().getString("controllerOperationData");
        if(operationStr.equals("")){
            operationData = new HashMap<>();
        }else{
            operationData = JSON.parseObject(operationStr,new TypeReference<HashMap<String,Map<String,Long>>>() {});
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.item_allocation_controller:
                checkOperation("该操作将重新分配所有从机485地址，需等待较长（平均每个从机15秒左右）时间！",0);
                break;
            case R.id.item_expand_controller:
                checkOperation("该操作将为新增的从机分配485地址，确认继续吗？",1);
                break;
            case R.id.item_clean_controller:
                checkOperation("该操作会清楚所有从机的485地址，确认继续吗？",2);
                break;
            case R.id.item_reset_controller:
                checkOperation("您将重启主机，确认继续吗？",3);
                break;
            case R.id.item_all_search:
                operationController(4);
                break;
            case R.id.item_wifi_change:
                operationController(5);
                break;
        }
    }

    private void checkOperation(String tips,int value){
        int time = 300 * 1000;
        if(value == 9){
            time = 30 * 1000;
        }
        if(operationData.get(controllerSerialNo) != null && operationData.get(controllerSerialNo).get(String.valueOf(value)) != null && System.currentTimeMillis() - operationData.get(controllerSerialNo).get(String.valueOf(value)) < time){
            toast("操作过于频繁，请稍后在尝试");
        }else{
            showDeleteHintDialog(tips,value);
        }
    }

    private BaseDialog mConfirmCancelHintDialog;
    private ConfirmCancelHintDialog.Builder mConfirmCancelHintDialogBuilder;
    private void showDeleteHintDialog(String tips, int value) {
        if (mConfirmCancelHintDialog == null) {
            mConfirmCancelHintDialogBuilder = new ConfirmCancelHintDialog.Builder(getActivity());
            mConfirmCancelHintDialogBuilder.setRightText(R.string.common_confirm);
            mConfirmCancelHintDialog = mConfirmCancelHintDialogBuilder.create();
        }
        mConfirmCancelHintDialogBuilder.setListener(new ConfirmCancelHintDialog.OnListener() {
            @Override
            public void onLeftClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
            }

            @Override
            public void onRightClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
                operationController(value);
            }
        });
        mConfirmCancelHintDialogBuilder.setContent(tips);
        mConfirmCancelHintDialog.show();
    }

    private void operationController(int value){
        LLHttpManager.operationController(this, controllerSerialNo, AppApplication.getInstance().getCurrentHouseSerialNo(), value, new HttpCallback<HttpData<Void>>(this) {
            @Override
            public void onStart(Call call) {
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                toast("操作成功");
                if(operationData.get(controllerSerialNo) == null){
                    Map<String,Long> map = new HashMap<>();
                    operationData.put(controllerSerialNo,map);
                }
                operationData.get(controllerSerialNo).put(String.valueOf(value),System.currentTimeMillis());
                Gson gson = new Gson();
                SPUtils.getInstance().put("controllerOperationData",gson.toJson(operationData));
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {

            }
        });
    }
}
